import { getUserAuth } from '@/api/login';
import { showModal } from '@/utils/message';
import store from '../store';

const TokenKey = 'crm-token';

export function getToken() {
  return Cookies.get(TokenKey);
}

export function setToken(token) {
  return Cookies.set(TokenKey, token, {
    expires: 7
  });
}

export function removeToken() {
  return Cookies.remove(TokenKey);
}

let notifyUserTimer = null;
export function pollingUser(once = false) {
  if (once) {
    getUserAuth().then(res => {
      if (res.code === 200 && res.data) {
        notify(res.data);
      }
    });
  } else {
    const PollingTime = 30000;
    if (notifyUserTimer) clearTimeout(notifyUserTimer);
    notifyUserTimer = setTimeout(() => {
      getUserAuth().then(res => {
        pollingUser();
        if (res.code === 200 && res.data) {
          notify(res.data);
        }
      });
    }, PollingTime);
  }
}

function notify(curAuthList) {
  const oldAuthList = store.state.user.roles;
  const readAuthList = store.state.user.readAuthList;
  curAuthList.splice(0, 0, oldAuthList[0]);
  const addAuth = _.difference(curAuthList, oldAuthList);
  const reduceAuth = _.difference(oldAuthList, curAuthList);

  const diffAuth = [...addAuth, ...reduceAuth];
  if (diffAuth && diffAuth.length) {
    store.commit('SET_ROLES', curAuthList);

    const diffReadAuth = [];
    diffAuth.forEach((diffVal) => {
      for (let i = 0; i < readAuthList.length; i++) {
        const readVal = readAuthList[i];
        if (diffVal.indexOf(readVal) >= 0) {
          diffReadAuth.push(diffVal);
          break;
        }
      }
    });
    if (diffReadAuth && diffReadAuth.length) {
      if (notifyUserTimer) clearTimeout(notifyUserTimer);
      showMsg();
    }
  }
}

function showMsg(msgData) {
  const msg = `${msgData || '您的权限有变化，是否刷新页面？'}`;
  showModal(msg, '', {}, true).then(() => {
    window.location.reload();
  }).catch(() => {
    pollingUser();
  });
}
